/*
 * @Author: Dufen~123 dufen.0
 * @Date: 2024-11-26 15:28:40
 * @LastEditors: Dufen~123 dufen.0
 * @LastEditTime: 2024-11-26 15:46:20
 * @FilePath: \my-app\src\components\Echarts\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useRef, useEffect } from "react";
import * as echarts from "echarts";

//配置echart
const axisOption = {
  // 图例文字颜色
  textStyle: {
    color: "#333",
  },
  // 提示框
  tooltip: {
    trigger: "axis",
  },
  xAxis: {
    type: "category", // 类目轴，离散数据
    data: [],
    axisLine: {//坐标轴线
      lineStyle: {
        color: "#17b3a3",
      },
    },
    axisLabel: {//每一个坐标
      interval: 0,//坐标间隔
      color: "#333",
    },
  },
  yAxis: [
    {
      type: "value",//数值轴，连续数据
      axisLine: {
        lineStyle: {
          color: "#17b3a3",
        },
      },
    },
  ],
  color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
  series: [],
};

const normalOption = {
  tooltip: {
    trigger: "item",
  },
  color: [
    "#0f78f4",
    "#dd536b",
    "#9462e5",
    "#a6a6a6",
    "#e1bb22",
    "#39c362",
    "#3ed1cf",
  ],
  series: [],
};

const Echarts = ({ style, chartData, isAxisChart = true }) => {
  //chartData是数据源，isAxisChart是要判断有没有坐标轴
  //获取dom实例
  const echartRef = useRef(); //用ref获取动态dom实例
  let echartObj = useRef(null); //这个对象在数据变化时不会造成页面重新渲染
  //普通的变量不会监听到响应式变化，useState创建的变量又会造成页面重新渲染
  //因为useState在数据变化时是整个对象都重新创建，而useRef还是同一个对象
  useEffect(() => {
    let options;
    //初始化echarts实例
    echartObj.current = echarts.init(echartRef.current); //echartRef.current就是DOM元素
    //设置options
    if (isAxisChart) {
      axisOption.xAxis.data = chartData.xData;
      axisOption.series = chartData.series;
      options = axisOption;
    } else {
      normalOption.series = chartData.series;
      options = normalOption;
    }
    echartObj.current.setOption(options);
  }, [chartData]);
  return <div style={style} ref={echartRef}></div>;
};
export default Echarts;
